package com.yc.chatroom.server.service;

import javax.security.auth.message.AuthException;

import com.yc.chatroom.common.Constant;
import com.yc.chatroom.common.dto.ResultDto;
import com.yc.chatroom.server.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yc.chatroom.common.dto.LoginDto;
import com.yc.chatroom.common.dto.LoginResponse;
import com.yc.chatroom.common.util.MD5SignUtil;
import com.yc.chatroom.server.ServerManager;
import com.yc.chatroom.server.dao.UserRepositoryDao;
import com.yc.chatroom.server.pojo.po.UserPo;
import com.yc.chatroom.server.util.JWTUtil;
import com.yc.chatroom.server.util.LocalCacheUtil;

import java.util.Date;

@Service
public class AuthService {
	
	private ServerManager mainServer;
	
	@Autowired
	private UserRepositoryDao userRepositoryDao;
	

	/**
	 * 登录接口
	 * @param dto
	 * @return
	 * @throws AuthException 
	 */
	public ResultDto loginHandler(LoginDto dto) throws AuthException {
		//解析接收数据
		//查询数据库看是否有该用户
		UserPo user = userRepositoryDao.findByUserAccount(dto.getAccount());
		if (null == user) {
			throw new AuthException("用户不存在");
		}
		if (!dto.getPassword().equals(MD5SignUtil.toMd5(user.getUserPassword()))) {
			throw new AuthException("用户或密码输入错误");
		}

		//判断用户是否已经登陆
//		boolean onlineFlag = false;

		//如果有则更新用户最新登录时间
		Long now = new Date().getTime();
		user.setUserLastLoginTime(now);
		user.setLastModifyTime(now);
		userRepositoryDao.save(user);
		
		//给用户生成token
		String token = JWTUtil.getToken(user.getUserId().toString(), StringUtil.getUuid());
		
		//把userid, token放到缓存，在三秒内等待客户端建立tcp连接
		LocalCacheUtil.put(1, token);

		ResultDto result = new ResultDto();
		result.setMsg("登陆成功");
//		result.setData(new LoginResponse(token));
		return result;
	}

	/**
	 *
	 * @param dto
	 * @return
	 * @throws AuthException
	 */
	public ResultDto checkLogin(LoginDto dto) throws AuthException {
		ResultDto result = new ResultDto();
		//查询数据库看是否有该用户
		UserPo user = userRepositoryDao.findByUserAccount(dto.getAccount());
		if (null == user) {
			result.setCode(Constant.RESULT_CODE_SESSION_EXPIRED);
			result.setMsg("用户不存在");
			return result;
		}
		if (!dto.getPassword().equals(MD5SignUtil.toMd5(user.getUserPassword()))) {
			result.setCode(Constant.RESULT_CODE_SESSION_EXPIRED);
			result.setMsg("账号或密码错误");
			return result;
		}

		result.setMsg("登陆成功");
		result.setData(user);
		return result;
	}
}
